package aop;

import com.fasterxml.jackson.databind.ObjectMapper;
import entity.MyResult;
import entity.Resource;
import entity.Role;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.invoke.MethodHandle;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author bigpeng
 * @create 2020-06-16-11:15
 */
public class PermissionInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //HandlerMethod 控制层方法,如果不是控制层请求，直接放行
        if(!(handler instanceof HandlerMethod)){ return true; }
        HandlerMethod methodHandle= (HandlerMethod) handler;
        //控制层方法对象
        Method method = methodHandle.getMethod();
        //获取控制层方法上的注解
        RequiredPermission annotation = method.getAnnotation(RequiredPermission.class);
        //没有注解，不需要做权限控制
        if(annotation==null){ return true; }
        //获取方法需要的权限值
        String permission = annotation.value();
        //获取到权限信息
        Role role = (Role) request.getSession().getAttribute("role");
        List<Resource> resourceList = role.getResourceList();
        for (Resource resource : resourceList) {
            //如果权限值匹配，则放行
            if(permission.equals(resource.getPermission())){
                return  true;
            }
        }
        //判断是否是ajax请求，如果是ajax请求，需要返回json数据
        String header = request.getHeader("X-Requested-With");
        if(header!=null&&header.equalsIgnoreCase("XMLHttpRequest")){
            //封装一个响应对象
            MyResult<String> result=new MyResult<>(403,"没有权限操作");
            //设置响应内容为json
            response.setContentType("application/json;charset=UTF-8");
            // 通过Jackson 将对象转换为json字符串
            ObjectMapper objectMapper=new ObjectMapper();
            String s = objectMapper.writeValueAsString(result);
            //通过response响应数据
            response.getWriter().write(s);
            return false;
        }
        //跳转到没有权限的页面
        response.sendRedirect(request.getContextPath()+"/403.jsp");
        return false;
    }
}
